﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.IO;
using AutoCompleteText;
using System.Diagnostics;
using WindowsInstaller;
using System.Threading;
using System.Windows.Media.Animation;
using System.Windows.Forms;
namespace ISUM_V2
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public ScreenKeyboard _ScreenKeyboard = null;
        public ScreenMouse _ScreenMouse = null;
        public Signal _Signal = null;
        public static bool _IsSignal = false;
        public static bool _IsCommunication = false;
        private SerialCommunication ip = null;

        public static string _RunPath = System.Windows.Forms.Application.StartupPath;

        private MorseCodeFileModule _Mcfm { get; set; }
        private ConnectType _ConnectType { get; set; }
        private string _CheckString { get; set; }

        public MainWindow ()
        {
            this.InitializeComponent();
			
			//new CustomKeyboard().ShowDialog();
			
            this.Closed += new EventHandler( MainWindow_Closed );
            this.Btn_Glasses.Click+=new RoutedEventHandler(Btn_Glasses_Click);
            this.Btn_Switch.Click+=new RoutedEventHandler(Btn_Switch_Click);
            this.ContentRendered += new EventHandler( MainWindow_ContentRendered );


            UC_MessageBox.Btn_OK.Click += new RoutedEventHandler( Btn_OK_Click );
            UC_MessageBox.Btn_Cancel.Click += new RoutedEventHandler( Btn_Cancel_Click );
            UC_MessageBox.Tb_Message.Text = "장치와의 연결에 실패하였습니다.\r\n다시 연결하시겠습니까?";
            _Mcfm = MorseCodeFileModule.getInstance();
            _ScreenKeyboard = new ScreenKeyboard(this);
            _ScreenMouse = new ScreenMouse(this);

            _Signal = new Signal();
            MainWindow._IsSignal = true;

            string path = GetDoubleParent() + "/Connect.data";
            FileInfo _finfo = new FileInfo( path );

            if ( _finfo.Exists )
            {
                _ConnectType = (ConnectType)_Mcfm.readFile( path );
            }
            else
            {
                _ConnectType = new ConnectType();
            }

         
            //Console.WriteLine(GetDoubleParent());
            //startup("ISUM", true);
        }

        void MainWindow_ContentRendered ( object sender, EventArgs e )
        {
             
            if (_ConnectType._SelectDevice == 1)
            {
                _CheckString = "ISUM";
                HideCanvasSelect();
                new Thread(new ThreadStart(ConnectBluetoothDelegate)).Start();
            }
            else if (_ConnectType._SelectDevice == 2)
            {
                _CheckString = "ISUN";
                HideCanvasSelect();
                new Thread(new ThreadStart(ConnectBluetoothDelegate)).Start();
            }

        }
        public static string GetDoubleParent()
        {
            string path = System.IO.Directory.GetParent(_RunPath).ToString();            
            return System.IO.Directory.GetParent(path).ToString();                        
        }

        /// <summary>
        /// Startup manager method
        /// 
        /// if enable is true : Add
        /// else Remove
        /// </summary>
        /// <param name="AppName"></param>
        /// <param name="enable"></param>
        private void AddRegister(bool enable)
        {
            string runKey = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run";
            Microsoft.Win32.RegistryKey startupKey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(runKey);

            if (enable)
            {
                if (startupKey.GetValue("ISUM") == null)
                {
                    // Add startup
                    startupKey.Close();
                    startupKey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(runKey, true);
                    startupKey.SetValue("ISUM", System.Windows.Forms.Application.ExecutablePath.ToString());
                    startupKey.Close();
                    Console.WriteLine("OK");
                }
            }

            else
            {
                // Remove startup
                startupKey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(runKey, true);
                startupKey.DeleteValue("ISUM", false);
                startupKey.Close();
            }
        }

        public void HideCanvasSelect()
        {
            Canvas_Select.Visibility = Visibility.Hidden;
        }
        void  Btn_Switch_Click(object sender, RoutedEventArgs e)
        {
 	        _ConnectType._SelectDevice=2;
            _CheckString = "ISUN";
            SaveConnectInfo();
            HideCanvasSelect();
            new Thread(new ThreadStart(ConnectBluetoothDelegate)).Start();
        }

        void  Btn_Glasses_Click(object sender, RoutedEventArgs e)
        {
            _ConnectType._SelectDevice=1;
            _CheckString = "ISUM";
            SaveConnectInfo();
            HideCanvasSelect(); 
            new Thread(new ThreadStart(ConnectBluetoothDelegate)).Start();
        }

        private void SaveConnectInfo()
        {
            _Mcfm.writeFile(GetDoubleParent()+"/Connect.data", _ConnectType);
        }

        
	

        public void ConnectBluetoothDelegate()
        {
            this.Dispatcher.BeginInvoke( new NoParamDelegate( ConnectBluetooth ) );
        }
        private delegate void NoParamDelegate ();
     

        void Btn_Cancel_Click ( object sender, RoutedEventArgs e )
        {
            KillProcess();
        }

        void Btn_OK_Click ( object sender, RoutedEventArgs e )
        {
			
            ConnectBluetooth();
        }

	
        private void ConnectBluetooth ()
        {

			
            foreach ( string portnum in System.IO.Ports.SerialPort.GetPortNames() )
            {
                try
                {
                    Console.WriteLine( "연결 시도 포트 : " + portnum );
                    ip = new SerialCommunication( this, portnum );
                    ip.SerialStart();
                    
                    ip.SendData( "ISUM" );
                    System.Threading.Thread.Sleep( 200 );

                    if (ip._InputData.Equals(_CheckString))

                    {
                        Console.WriteLine( "포트 연결 성공" );
                        MainWindow._IsCommunication = true;
                        break;
                    }
                    Console.WriteLine( "포트 연결 실패" );
					
                    ip.SerialStop();
                }
                catch ( Exception e ) { Console.WriteLine( e.StackTrace.ToString() ); }
            }

            if ( MainWindow._IsCommunication )
            {
                _ScreenKeyboard.Show();
                _ScreenKeyboard.Hide();
                _ScreenMouse.Show();

                this.Hide();
            }

            else
            {
                ShowMessageBox();  
			
            }
			
        }

        private void ShowMessageBox ()
        {
            UC_MessageBox.Visibility = Visibility.Visible;
        }

        private void HideMessageBox ()
        {
            UC_MessageBox.Visibility = Visibility.Hidden;
        }

        public void KillProcess ()
        {
            string processName = "ISUM_V2"; // .exe 는 빼셔야 되여~

            Process[] processes = Process.GetProcessesByName( processName );

            foreach ( Process process in processes )
            {

                process.Kill();

            }
        }

        public void MainWindow_Closed ( object sender, EventArgs e )
        {
            if ( this._ScreenKeyboard != null )
            {
                this._ScreenKeyboard.CloseAutoCompleteText();
                this._ScreenKeyboard.Close();
            }

            if ( this._ScreenMouse != null )
            {
                this._ScreenMouse.Close();
            }

            if ( this.ip != null )
            {
                this.ip.SerialStop();
            }

            KillProcess();

        }
    }
}